package com.rm.wechatapp.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.rm.wechatapp.entity.AccountRelaFavorite;
import com.rm.wechatapp.entity.VO.QuestionVO;
import com.rm.wechatapp.mapper.AccountRelaFavoriteMapper;
import com.rm.wechatapp.service.IAccountUserService;
import com.rm.wechatapp.service.IOnQuestionService;
import com.rm.wechatapp.service.IWeixinService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api/exam")
public class WeTempExamController {

    @Autowired
    IOnQuestionService coreQuestionService;

    @Autowired
    IWeixinService weixinService;

    @Autowired
    IAccountUserService accountUserService;

    @Autowired
    AccountRelaFavoriteMapper accountRelaFavoriteMapper;

    @GetMapping("/{owner_id}")
    @ResponseBody
    public List<QuestionVO> getQuestions(
            @PathVariable("owner_id") String ownerId,
            @RequestParam("code") String code) throws JsonProcessingException {
        List<QuestionVO> list =  coreQuestionService.selectByOwnerIdToVO(Long.valueOf(ownerId));
        System.out.println("第一次题目列表"+list);
        String openId = weixinService.getOpenId(code);
        Long userId = accountUserService.getByOpenId(openId).getId();
        Collections.shuffle(list);
        list = list.subList(0,100);
        for(QuestionVO ele : list){
            QueryWrapper<AccountRelaFavorite> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", userId)
                    .eq("question_id", ele.getReal_id());
            AccountRelaFavorite accountRelaFavorite = accountRelaFavoriteMapper.selectOne(queryWrapper);
            if(accountRelaFavorite == null){
                ele.setFavorite(false);
            }else{
                ele.setFavorite(true);
            }
            System.out.println("修改后的这道题: "+ele);
        }
        System.out.println("第二次题目列表"+list);
        return list;
    }

}
